<template>
  <div class="myInformation_container">
    <div class="sideright">
      <div class="top-div">
        <span>个人信息</span>
      </div>
      <div class="botton-div">
        <div class="head-portrait-div">
          <img :src="userInfo.uImg" alt="无法加载图片" />
          <span @click="uploadHeader">修改头像</span>
        </div>
        <div class="grxx-div">
          <div class="title">
            <span>基础资料</span>
            <span @click="editInfo">编辑</span>
          </div>
          <div>
            <span>昵称: {{ userInfo.uUsername }}</span>
          </div>
          <div>
            <span>生日: {{ userInfo.uBirthday }}</span>
          </div>
          <div>
            <span>性别: {{ userInfo.uSex }}</span>
          </div>
          <div><span>高级设置</span></div>
          <div>
            <span>账号地区：{{ userInfo.uArea }}</span>
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="编辑个人信息"
      :visible.sync="infoDialogVisible"
      center
      width="25%"
      :before-close="infoHandleClose">
      <el-form :model="editInfoForm" :rules="editInfoRules" ref="editInfoRef" label-width="80px" class="demo-ruleForm">
        <el-form-item label="用户昵称" prop="uUsername" :error="errorMsg">
          <el-input v-model.trim="editInfoForm.uUsername" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" required>
          <el-form-item prop="uBirthday">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model.trim="editInfoForm.uBirthday"
              value-format="yyyy-MM-dd"
              style="width: 100%"></el-date-picker>
          </el-form-item>
        </el-form-item>
        <el-form-item label="性别" prop="uSex">
          <el-radio-group v-model.trim="editInfoForm.uSex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账号地区" required>
          <el-form-item prop="uAreaId">
            <el-cascader
              v-model.trim="editInfoForm.uAreaId"
              :options="options"
              :props="{ expandTrigger: 'hover' }"
              filterable
              clearable
              placeholder="试试搜索：福建 / 福州 / 闽侯县"></el-cascader>
          </el-form-item>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm">提 交</el-button>
          <el-button @click="resetForm">重 置</el-button>
          <el-button @click="closeForm">取 消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog
      title="上传头像"
      :visible.sync="uploadDialogVisible"
      center
      width="25%"
      :before-close="uploadhandleClose">
      <el-upload
        class="upload-demo"
        :headers="headerObj"
        action="http://127.0.0.1:9999/user/uploadHeader"
        drag
        :before-upload="beforeAvatorUpdate"
        :on-success="AvatorUpdateSuccess">
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传jpg/png文件, 且不超过2MB</div>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script>
import provAndCity from '@/assets/static/area.json'
// import { mixin } from '@/mixin'
export default {
  name: 'myInformation',
  // mixins: [mixin],
  data() {
    return {
      options: [],
      userInfo: {},
      // 上传用户头像的请求头
      headerObj: {
        Authorization: window.localStorage.getItem('token')
      },
      infoDialogVisible: false,
      uploadDialogVisible: false,
      editInfoForm: {
        uUsername: '',
        uBirthday: '',
        uSex: '',
        uAreaId: [],
        uArea: ''
      },
      errorMsg: '',
      editInfoRules: {
        uUsername: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        uBirthday: [{ required: true, message: '请选择日期', trigger: 'change' }],
        uSex: [{ required: true, message: '请选择性别', trigger: 'change' }],
        uAreaId: [{ required: true, message: '请选择地区', trigger: 'change' }]
      }
    }
  },
  mounted() {
    this.options = provAndCity
  },
  created() {
    this.getUserInfo()
  },
  methods: {
    getUserInfo() {
      this.$http
        .get('/user/me')
        .then(res => {
          if (res.state === false) {
            return
          }
          this.userInfo = res.data
        })
        .catch(err => this.$message.error(err))
    },
    infoHandleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.$refs.editInfoRef.resetFields()
          done()
        })
        .catch(_ => {})
    },
    uploadhandleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => {})
    },
    editInfo() {
      this.editInfoForm.uUsername = this.userInfo.uUsername
      this.editInfoForm.uBirthday = this.userInfo.uBirthday
      this.editInfoForm.uSex = this.userInfo.uSex
      console.log(this.editInfoForm.uArea)
      this.infoDialogVisible = true
    },
    submitForm() {
      this.$refs.editInfoRef.validate(valid => {
        if (valid) {
          let nameArr = []
          let value = this.editInfoForm.uAreaId
          for (let j = 0; j < this.options.length; j++) {
            if (value[0] === this.options[j].value) {
              // 比较两者的id是否相等
              nameArr.push(this.options[j].label)
              for (let k = 0; k < this.options[j].children.length; k++) {
                if (value[1] === this.options[j].children[k].value) {
                  nameArr.push(this.options[j].children[k].label)
                  for (let t = 0; t < this.options[j].children[k].children.length; t++) {
                    if (value[2] === this.options[j].children[k].children[t].value) {
                      nameArr.push(this.options[j].children[k].children[t].label)
                      break
                    }
                  }
                  break
                }
              }
              break
            }
          }
          this.editInfoForm.uArea = nameArr.toString()
          this.$http
            .post('/user/updateUserInfo', this.editInfoForm)
            .then(res => {
              console.log(res)
              if (res.state === false) {
                this.errorMsg = res.errorMsg
                return
              }
              this.getUserInfo()
              this.infoDialogVisible = false
              this.$message.success(res.data)
            })
            .catch(err => this.$message.error(err))
        } else {
          return false
        }
      })
    },
    resetForm() {
      this.$refs.editInfoRef.resetFields()
    },
    closeForm() {
      this.$refs.editInfoRef.resetFields()
      this.infoDialogVisible = false
    },
    uploadHeader() {
      this.uploadDialogVisible = true
    },
    // 上传图片之前的校验
    beforeAvatorUpdate(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJPG) {
        this.$message.error('上传的图片只能是png或jpg格式')
        return isJPG
      }
      const isOver = file.size / 1024 / 1024 < 2
      if (!isOver) {
        this.$message.error('上传的图片大小不能超过2MB')
        return isOver
      }
      return true
    },
    AvatorUpdateSuccess(res) {
      console.log(res)
      // if (response.code === 1) {
      //   this.$message.success(response.msg)
      // } else {
      //   this.$message.success(response.msg)
      // }
    }
  }
}
</script>

<style lang="less" scoped>
.sideright {
  width: 73%;
  padding: 5%;
  float: right;
  background-color: #fff;
  border: 1px solid #dbdbdb;
  .top-div {
    padding-bottom: 10px;
    border-bottom: 1px solid #dbdbdb;
    span {
      font-size: 1.5em;
    }
  }
  .botton-div {
    display: flex;
    align-items: center;
  }
  .head-portrait-div {
    flex-grow: 2;
    display: flex;
    align-items: center;
    flex-direction: column;
    img {
      width: 92px;
      height: 92px;
      padding: 1px;
      border-radius: 46px;
      border: 2px solid #dbdbdb;
    }
    span {
      display: block;
      cursor: pointer;
      padding-top: 5px;
      color: #009688;
      // color: #a10000;
    }
  }
  .grxx-div {
    flex-grow: 8;
    div {
      padding: 10px 0 10px 0;
      border-bottom: 1px solid #dbdbdb;
    }
    div:nth-child(1) {
      display: flex;
      font-weight: bold;
      align-items: center;
      padding: 30px 0 20px 0;
      span:nth-child(1) {
        flex-grow: 1;
        font-size: 20px;
      }
      span:nth-child(2) {
        cursor: pointer;
        // color: #a10000;
        color: #009688;
        font-weight: normal;
      }
    }
    div:nth-child(5) {
      font-weight: bold;
      padding: 30px 0 20px 0;
      span {
        font-size: 20px;
      }
    }
  }
}
.el-cascader {
  width: 100%;
}

.upload-demo {
  text-align: center;
}
</style>
